package com.itheima.controller;

import com.itheima.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//@ControllerAdvice   //拦截controller
public class GlobalExceptionHandler {


    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    //配置拦截的异常类型
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e){
        logger.error("出错了........",e);
        return new Result(false,"执行出错了");
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgument(MethodArgumentNotValidException e){
        StringBuffer sb =  new StringBuffer();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            sb.append(fieldError.getField() + ":" + fieldError.getDefaultMessage()+"\r\n");
        }
        return new Result(false,sb.toString());
    }


    //配置拦截的异常类型
    public Result runtime(Exception e){
        logger.error("不符合要求....",e);
        return new Result(false,e.getMessage());
    }
}